//
//  LoginViewModel.m
//  MVMMLoginDemo
//
//  Created by jianzhao4 on 2017/9/18.
//  Copyright © 2017年 Xwoder. All rights reserved.
//

#import "LoginViewModel.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import <AFNetworking/AFNetworking.h>

@implementation LoginViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupBind];
    }
    return self;
}

// 初始化绑定
- (void)setupBind {
    // Combines signals using +combineLatest:,
    // then reduces the resulting tuples into a single value using -reduceEach:
    _enableLoginSignal = [RACSignal combineLatest:@[RACObserve(self.account, username), RACObserve(self.account, password)] reduce:^NSNumber *(NSString *username, NSString *password) {
        NSLog(@"username = %@, password = %@", username, password);
        return @(username.length > 0 && password.length > 0);
    }];
    
    // 处理登录业务逻辑
    _loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSObject * _Nullable input) {
        NSLog(@"点击了登录");
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [subscriber sendNext:@"登录成功"];
                [subscriber sendCompleted];
            });
            return nil;
        }];
    }];
    
    // 监听登录产生的数据
    [_loginCommand.executionSignals.switchToLatest subscribeNext:^(NSString *x) {
        if ([x isEqualToString:@"登录成功"]) {
            NSLog(@"登录成功");
        }
    }];
    
    // 监听登录状态
    [[_loginCommand.executing skip:1] subscribeNext:^(NSNumber *x) {
        if ([x isEqualToNumber:@(YES)]) {
            // 正在登录ing...
            // 用蒙版提示
            NSLog(@"显示 HUD");
        } else {
            // 登录成功
            // 隐藏蒙版
             NSLog(@"隐去 HUD");
        }
    }];
}

#pragma mark - Lazy Loading

- (Account *)account {
    if (!_account) {
        Account *account = [[Account alloc] init];
        _account = account;
    }
    return _account;
}

@end
